package com.itheima.server.service;

import cn.hutool.core.collection.CollUtil;
import com.itheima.commons.utils.Constants;
import com.itheima.dubbo.api.ActivityApi;
import com.itheima.dubbo.api.CommentsApi;
import com.itheima.dubbo.api.UserInfoApi;
import com.itheima.dubbo.api.VisitorsApi;
import com.itheima.model.domain.Activity;
import com.itheima.model.domain.UserInfo;
import com.itheima.model.enums.CommentType;
import com.itheima.model.enums.LogTypeEnum;
import com.itheima.model.mongo.Comment;
import com.itheima.model.mongo.Visitors;
import com.itheima.model.vo.CommentVo;
import com.itheima.model.vo.ErrorResult;
import com.itheima.model.vo.PageResult;
import com.itheima.model.vo.VisitorsVo;
import com.itheima.server.exception.BusinessException;
import com.itheima.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CommentsService {
    @DubboReference
    private CommentsApi commentsApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @DubboReference
    private VisitorsApi visitorsApi;
    @DubboReference
    private ActivityApi activityApi;

    //保存评论（保存评论，并将动态的数据更新）
    public void saveComments(String movementId, String comment) {
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));//将String类型的movementId自动转换为ObjectId类型
        comment1.setCommentType(CommentType.COMMENT.getType());//通过枚举获取是评论还是点赞还是收藏
        comment1.setContent(comment);
        comment1.setUserId(UserHolder.getUserId());

        Integer count = commentsApi.save(comment1);//保存评论，并返回该动态的评论总数

    }

    /*查询评论列表*/
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //调用api查询评论列表
        List<Comment> comments = commentsApi.findComments(movementId, CommentType.COMMENT, page, pagesize);
        //判断结果是否存在
        if (CollUtil.isEmpty(comments)) {
            return new PageResult();
        }
        //根据用户id查询用户详情
        //构造vo
        List<CommentVo> commentVos = new ArrayList<>();
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> userInfos = userInfoApi.findByIds(userIds, null);
        if (!CollUtil.isEmpty(userInfos)) {
            for (Comment comment : comments) {
                UserInfo userInfo = userInfos.get(comment.getUserId());
                commentVos.add(CommentVo.init(userInfo, comment));
            }
        }
        PageResult pageResult = new PageResult(page, pagesize, (long) comments.size(), commentVos);
        return pageResult;
    }

    //点赞
    public Integer likeComment(String id) {
        //判断是否已经点赞（点赞就抛出异常）
        boolean res = commentsApi.hasComment(id, UserHolder.getUserId(), CommentType.LIKE);
        if (res) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //保存点赞数据到mongodb
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(id));//将String类型的movementId自动转换为ObjectId类型
        comment1.setCommentType(CommentType.LIKE.getType());//通过枚举获取是评论还是点赞还是收藏
        comment1.setUserId(UserHolder.getUserId());
        Integer count = commentsApi.save(comment1);//保存点赞，并返回该动态的点赞总数

        //TODO:2022.6.22改添加用户活跃状态
        String nowDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        Activity activity = new Activity();
        activity.setUserId(UserHolder.getUserId());
        activity.setActivityDate(nowDate);
        activity.setDate(new Date());
        activity.setActivityType(LogTypeEnum.MOVEMENTS_LIKE.getValue());
        activityApi.save(activity);

        //保存到redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    //取消点赞
    public Integer disLikeComment(String id) {
        //判断是否已经点赞（未点赞就抛出异常）
        boolean res = commentsApi.hasComment(id, UserHolder.getUserId(), CommentType.LIKE);
        if (!res) {
            throw new BusinessException(ErrorResult.disLikeError());//没点赞，就不能取消点赞
        }
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(id));//将String类型的movementId自动转换为ObjectId类型
        comment1.setCommentType(CommentType.LIKE.getType());//通过枚举获取是评论还是点赞还是收藏
        comment1.setUserId(UserHolder.getUserId());
        Integer count = commentsApi.delete(comment1);//删除点赞，并返回该动态的点赞总数

        //TODO:添加用户活跃状态
        String nowDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        Activity activity = new Activity();
        activity.setUserId(UserHolder.getUserId());
        activity.setActivityDate(nowDate);
        activity.setActivityType(LogTypeEnum.MOVEMENTS_UNLIKE.getValue());
        activity.setDate(new Date());
        activityApi.save(activity);

        //删除redis中的缓存
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }

    public Integer loveComment(String id) {
        //判断是否已经点赞（点赞就抛出异常）
        boolean res = commentsApi.hasComment(id, UserHolder.getUserId(), CommentType.LOVE);
        if (res) {
            throw new BusinessException(ErrorResult.loveError());
        }
        //保存点赞数据到mongodb
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(id));//将String类型的movementId自动转换为ObjectId类型
        comment1.setCommentType(CommentType.LOVE.getType());//通过枚举获取是评论还是点赞还是收藏
        comment1.setUserId(UserHolder.getUserId());
        Integer count = commentsApi.save(comment1);//保存点赞，并返回该动态的点赞总数
        //保存到redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    public Integer unLoveComment(String id) {
        //判断是否已经点赞（未点赞就抛出异常）
        boolean res = commentsApi.hasComment(id, UserHolder.getUserId(), CommentType.LOVE);
        if (!res) {
            throw new BusinessException(ErrorResult.loveError());//没点赞，就不能取消点赞
        }
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(id));//将String类型的movementId自动转换为ObjectId类型
        comment1.setCommentType(CommentType.LOVE.getType());//通过枚举获取是评论还是点赞还是收藏
        comment1.setUserId(UserHolder.getUserId());
        Integer count = commentsApi.delete(comment1);//删除点赞，并返回该动态的点赞总数
        //删除redis中的缓存
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }

    public List<VisitorsVo> queryVisitorsList() {
        //查询上次看的访问列表时间
        String key = Constants.VISITORS;
        String hashKey = String.valueOf(UserHolder.getUserId());
        String value = (String) redisTemplate.opsForHash().get(key, hashKey);
        Long date = StringUtils.isEmpty(value) ? null : Long.valueOf(value);
        //调用api查询数据列表
        List<Visitors> visitorss = visitorsApi.queryVisitors(UserHolder.getUserId(), date);
        redisTemplate.opsForHash().put(key, hashKey, String.valueOf(System.currentTimeMillis()));//保存这次看的访问列表时间

        if (CollUtil.isEmpty(visitorss)) {
            return new ArrayList<>();
        }
        //提取用户id
        List<Long> visitorsUserId = CollUtil.getFieldValues(visitorss, "visitorUserId", Long.class);
        //查看用户详情
        Map<Long, UserInfo> userInfos = userInfoApi.findByIds(visitorsUserId, null);
        //构造返回
        List<VisitorsVo> visitorsVos = new ArrayList<>();
        for (Visitors visitors : visitorss) {

            //排除自己的id
            if(!visitors.getVisitorUserId().equals(UserHolder.getUserId())) {
                visitorsVos.add(VisitorsVo.init(userInfos.get(visitors.getVisitorUserId()), visitors));
            }
        }
        return visitorsVos;
    }

    //评论点赞
    public Integer likeCount(String commentId) {
        Boolean hasComment = commentsApi.hasComment(commentId, UserHolder.getUserId(), CommentType.LIKE);
        //如果已点赞.抛出异常
        if (hasComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //3.调用api保存数据到Mongodb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(commentId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        //comment.set
        Integer count = commentsApi.saveComent(comment);
        //4.将当前用户的点赞状态存到redis当中,拼接redis的key
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    //取消评论点赞
    public Integer dislikeCount(String commentId) {
        //1.调用api查询用户是否已点赞
        Boolean hasComment = commentsApi.hasComment(commentId, UserHolder.getUserId(), CommentType.LIKE);
        //2.如果未点赞,抛出异常
        if (!hasComment) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //3.如果已经点赞,接着调用api,删除数据,返回点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(commentId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());

        Integer count = commentsApi.deleteCount(comment);
        //4.拼接redis中的的key,删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }
}
